package com.gouda.backend.controller;

import com.themis.dto.BackendSystemUserDto;
import com.themis.dto.FrontFunctionDto;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.gouda.backend.exception.ErrorCode;
import com.gouda.core.service.systemManage.SystemUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: souu
 * Date: 15-4-13
 * Time: 下午5:16
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/")
public class IndexController extends AbstractController {

    @Autowired
    private SystemUserService userService;

    @RequestMapping(value = "/index")
    public ModelAndView adminUserlogin(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("");
        final String uid = super.getAdminUserId(request);
        if (Strings.isNullOrEmpty(uid)) {
            mv.setViewName("login");
            return mv;
        }
        try{
            long userId = Long.valueOf(uid);
            List<FrontFunctionDto> privileges = userService.loadUserPrivileges(userId);
            //TODO need to load user button privileges
            mv.addObject("privileges", privileges);
        }catch (NumberFormatException e){
            super.delCookie(response, "adminId", null);
            mv.setViewName("login");
            return mv;
        }
        mv.setViewName("index");
        return mv;
    }

    @RequestMapping(value = "/login")
    public
    @ResponseBody
    Map<String, Object> login(@RequestParam(value = "email", required = false) String email,
                              @RequestParam(value = "passwd", required = false) String passwd, HttpServletRequest request,
                              HttpServletResponse response) {
        Map<String, Object> map = Maps.newHashMap();
        if (Strings.isNullOrEmpty(email) || Strings.isNullOrEmpty(passwd)) {
            map.put("code", ErrorCode.EC_400004.getCode());
            return map;
        }

        BackendSystemUserDto userDto = this.userService.login(email, passwd);
        if (userDto == null) {
            map.put("code", ErrorCode.EC_400004.getCode());
            return map;
        }

        super.addCookie(response, "adminId", userDto.getUserId() + "");
//        super.addCookie(response, "userType", userDto.getUserType()+"");
//        super.addCookie(response, "loginUserName", userDto.getUserName());
        map.put("code", "200");
        return map;
    }

}
